import axios from 'axios'
import qs from 'qs'
import { API_HOST, API_STATE, isDev, wechatAuth as auth } from './config.js'
import { getSign, removeAllCookie } from '@/common/common'

const instance = axios.create()
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
/**
 * @description 拦截器
 */
instance.interceptors.request.use((config) => {
  config.data = qs.stringify(config.data)
  if (!auth.accessToken && !isDev) {
    return new Promise((resolve, reject) => {
      auth.updateToken().then(token => {
        config.headers.token = auth.accessToken
        resolve(config)
      })
    })
  } else {
    config.headers.token = auth.accessToken || 'tst'
    return config
  }
})

// response 拦截器
instance.interceptors.response.use((response) => {
  if (response && response.data) {
    const res = response.data
    const { status } = res
    // token过期,重新取授权
    if (status === API_STATE.expired) {
      isDev && console.log('token无效或已过期')
      removeAllCookie()
      auth.redirectToAuth()
      return
    }
  }
  return response
})

/**
 * @description 异步转同步请求
 * @param url
 * @param params
 * @return {Promise<unknown>}
 */
export function ajax (url, params) {
  // 增加签名
  const sign = getSign(params)
  Object.assign(params, sign)
  return new Promise((resolve, reject) => {
    instance.post(`${API_HOST}${url}`, params).then(({ data }) => {
      resolve(data)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 获取基本信息
 * @param params
 * @returns {Promise<*>}
 */
export function getBaseInfo (params = {}) {
  return ajax('/hn/v4/Love/check', params)
}

/**
 * 上传作品
 * @param params
 * @returns {Promise<*>}
 */
export function uploadUserStory (params = {}) {
  return ajax('/hn/v4/Love/create', params)
}

/**
 * 抽奖
 * @param params
 * @returns {Promise<*>}
 */
export function getLottery (params = {}) {
  return ajax('/hn/v4/Love/lottery', params)
}

/**
 * 上传中奖信息
 * @param params
 * @returns {Promise<*>}
 */
export function postLotteryInfo (params = {}) {
  return ajax('/hn/v4/Love/bind', params)
}

/**
 * 获取中奖列表
 * @param params
 * @returns {Promise<*>}
 */
export function getAllPrizeList (params = {}) {
  return ajax('/hn/v4/Love/prize', params)
}

/**
 * 记录分享
 * @param params
 * @returns {Promise<*>}
 */
export function addShare (params = {}) {
  return ajax('/hn/v4/YxRecord/share', params)
}

/**
 * 是否填写信息
 * @param params
 * @returns {Promise<*>}
 */
export function checkUser (params = {}) {
  return ajax('/hn/v4/YxUser/check', params)
}
